import 'package:distribution_mall_flutter/entity/address/address_entity.dart';
import 'package:distribution_mall_flutter/generated/json/address_state.g.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/http/init.dart';
import 'package:distribution_mall_flutter/http/modules/address.dart';
import 'package:distribution_mall_flutter/pages/address/address_create_edit/address_created_edit.dart';
import 'package:distribution_mall_flutter/pages/address/domain/action_address_item_entity.dart';
import 'package:distribution_mall_flutter/pages/goods/checkout/checkout_provider.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/state/address_state.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'product_details_provider.g.dart';

///用户的地址列表
@riverpod
class UserAddress extends _$UserAddress {
  @override
  AddressState build() {
    ref.watch(checkOutPromotionCodesProvider);
    return AddressState();
  }

  Future<Result<AddressEntity>> initData() async {
    return (await AddressApi.pageQuery(
      1,
      50,
    ))
        .yes((value) {
      state = state.copyWith(addressList: value?.items ?? []);
    });
  }

  ///其实应该写到service
  void refresh() {
    initData();
  }

  Future<void> setAddressInfo(AddressItem? item) async {
    if (item == null) {
      state = state.copyWith()
        ..userSelectAddress = null
        ..addrDeTime = [];
    } else {
      state = state.copyWith(
          userSelectAddress: SelectAddressItem()
            ..item = item
            ..recipientName = '${item.recipientName}'
            ..phone = '${item.phone}'
            ..address =
                '${item.street} ${item.district} ${item.city} ${item.province}'
            ..virtualPostcode = '${item.virtualPostcode}');

      ///查询地址配送时效,异步查询
      AddressApi.getAddressDeliveryTime(item.virtualPostcode!).then((value) {
        List<AddressDeliveryTimeEntity>? data = value.data;
        if (data != null) {
          state = state.copyWith(addrDeTime: data);
        }
      });
    }

  }

  ///这里暂时这么写 后续写到service里
  Future<void> deleteAddress(AddressItem e) async {
    (await AddressApi.remove(e.distributorAddressId!)).yes((value) {
      state =
          state.copyWith(addressList: List.from(state.addressList)..remove(e));
    });
  }

  Future<ActionAddressItemBody?> createAndEditAddress(
      Map<String, dynamic> map, AddressActionType type) async {
    EPLoading.showLoadig();
    try {
      var result = type == AddressActionType.add
          ? await AddressApi.add(map)
          : await AddressApi.update(map);
      return result.data;
    } catch (e) {
      return null;
    } finally {
      EPLoading.dis();
    }
  }

  updateIsDef(Map<String, dynamic> map) async {
    EasyLoading.show(status: '${S.current.loading}...');
    EPLoading.showLoadig();
    try {
      bool bol = await AddressApi.updateIsDef(map);
      if (bol) initData();
    } catch (e) {
    }
    EPLoading.dis();
  }
}

///详情页是否展示引导页
@riverpod
class ProductDetailsShowGuide extends _$ProductDetailsShowGuide {
  @override
  bool build() {
    return false;
  }

  showGuide() {
    if (EPstorage.guide.get(GuideBoxKey.productGuide, defaultValue: true)) {
      state = true;
    }
  }

  closeGuide() {
    state = false;
    EPstorage.guide.put(GuideBoxKey.productGuide, false);
  }
}

@riverpod
class ProductDetailsAppBarProgress extends _$ProductDetailsAppBarProgress {
  @override
  double build(ScrollController scrollController) {
    listener() {
      double value = scrollController.offset / 200;
      state = value > 1 ? 1 : value;
    }

    scrollController.addListener(listener);
    ref.onDispose(() {
      scrollController.removeListener(listener);
    });
    return 0;
  }
}
